<?php 

/**
 * 将安全json转化过的str转化为原样html
 */
function str_to_html($str){
	$str = str_replace("&lt;","<",$str);
	$str = str_replace("&quot;", '"', $str);
	$str = str_replace("&gt;", ">", $str);
	$str = str_replace("&amp;", "&", $str);
	return $str;	
}

//获取月份
function getMonthNum( $date1, $date2, $tags='-' ){
	$date1 = explode($tags,$date1);
	$date2 = explode($tags,$date2);
	return abs($date1[0] - $date2[0]) * 12 + abs($date1[1] - $date2[1]);
}
/*
 * send 短信
* return -1:No user ,-3:短信数量不足  , -4:手机格式不正确 , 1:短信已经发送
*/
function SMS_SEND($mobile,$msg){
	$msg = mb_convert_encoding($msg, "GBK", "UTF-8");
	$url="http://sms.webchinese.cn/web_api/?Uid=amanwu&Key=2605afe65369a30b7f30&smsMob=$mobile&smsText=$msg";
	return SMSAPI($url);
}
//短信接口调用
function SMSAPI($url){
	if(function_exists('file_get_contents'))
	{
		$file_contents = file_get_contents($url);
	}
	else
	{
		$ch = curl_init();
		$timeout = 5;
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$file_contents = curl_exec($ch);
		curl_close($ch);
	}
	return $file_contents;
}


/**
 * 输出json，作为api接口的统一返回
 */
function _apiReturn($status,$info,$data,$url){
	// 返回JSON数据格式到客户端 包含状态信息
	header('Content-Type:application/json; charset=utf-8');
	header("Access-Control-Allow-Origin: *");  //跨域请求
	exit(json_encode(ajax_data_tpl($status,$info,$data,$url),0));
}

/**
 * 固定ajax数据返回格式，沿用thinkphp3.1版本的格式
 * @param unknown $status
 * @param unknown $info
 * @param unknown $data
 */
function ajax_data_tpl($status,$info,$data){
	$result = array(
		'status' => $status,
		'info' => $info,
		'data' => $data
	);
	return $result;
}
/**
 * 检测客户端传递过来的token
 * @param string $token
 */
function _check_token($token){
	return in_array($token, _create_token());
}

/**
 * 生成token
 */
function _create_token(){
	$config = C('API_TOEKN');
	$day1 = date("Y-m-d",time()); //今天 ，标准token
	$day2 = date("Y-m-d",strtotime("-1 day"));//昨天 ，用于token时间戳容错
	$day3 = date("Y-m-d",strtotime("+1 day"));//明天，用于token时间戳容错
	$tokens[] = md5($config['name'].$day1.$config['key']);
	$tokens[] = md5($config['name'].$day2.$config['key']);
	$tokens[] = md5($config['name'].$day3.$config['key']);
	return $tokens;
}
/*
 * 当参数值为空的时候，返回默认值 
 * @param 参数 $data
 * @param 默认值 $default
 */
function _param_default($param,$default){
	if(!$param) $param = $default;
	return $param;
}

/*
 * 获取某分组下面的权限树
 * @param unknown $group
 * @return Ambigous <string, multitype:Ambigous <multitype:, boolean, multitype:multitype: > >
 */
function get_auth_tree($group){

	$m = M('AuthRule');
	$map['group'] = $group;
	$map['status'] = 1;

	$data = $m->cache(true, 60)->where($map)->order('listorder desc')->select();
	$tree = new \Think\Tree();

	$tree->init($data);
	$treedata = $tree->get_tree_array(0, $str);

	return $treedata;
}

/*
 * 获取某角色分组下面的权限树
* @param unknown $group
* @return Ambigous <string, multitype:Ambigous <multitype:, boolean, multitype:multitype: > >
*/
function get_auth_tree_by_role($group,$role){
	$m = M('AuthRule');
	$map['group'] = $group;

	if($role['title'] !== 'ROLE_SUPER_ADMIN'){
		$map['id'] = array('in',$role['rules']);
	}
	
	$data = $m->cache(true, 60)->where($map)->order('listorder desc')->select();
	$tree = new \Think\Tree();

	$tree->init($data);
	$treedata = $tree->get_tree_array(0, $str);

	return $treedata;
}

/*
 * 获取分页列表数据
 */
function _uiclist($model,$map,$cur,$size,$order,$isrelation){
	if(!$size) $size = C('PAGE_SIZE');

	if(!$order){
		$pk = $model->getPk();
		$order = "$pk desc";
	}

	$isrelation ? $isrelation = true : $isrelation = false;
	if($isrelation){
		$data['list'] = $model->where($map)->order($order)->page($cur.','.$size)->relation($isrelation)->select();
	}else{
		$data['list'] = $model->where($map)->order($order)->page($cur.','.$size)->select();
	}
	$data['count'] = $model->where($map)->count();
	return $data;
}

/*
 * 前端获取分页链接
 * @param unknown $total  记录总数
 * @param unknown $size   步长
 * @param unknown $cur    当前页面No
 * @param unknown $url    基础URL
 * @param unknown $theme  分页主题
 */
function _to_page($total ,$cur = 1, $size,$url,$theme = NULL,$config = array()){
	if(!$size) $size = C("PAGE_SIZE");
	if(!$config){
		$config  = array(
				'header' => '<span class="rows">共 %TOTAL_ROW% 条记录</span>',
				'prev'   => '<<',
				'next'   => '>>',
				'first'  => '1...',
				'last'   => '...%TOTAL_PAGE%',
				'theme'  => '%first%  %upPage%  %linkPage%  %downPage%  %end% <span>共%totalRow%条  %header% %nowPage%/%totalPage% 页  </span>',
				'html_suffix' => '.html',
		);
	}

	if(!$theme){
		$theme = $config['theme'];
	}

	$nowPage = $cur;
	$totalRows = $total;
	$rollPage = 5;
	$lastSuffix = true; // 最后一页是否显示总页数
	/* 计算分页信息 */
	$totalPages = ceil($total/$size);  //总页数
	if(!empty($totalPages) && $nowPage > $totalPages) {
		$nowPage = $totalPages;
	}
	/* 计算分页零时变量 */
	$now_cool_page      = $rollPage/2;
	$now_cool_page_ceil = ceil($now_cool_page);
	$lastSuffix && $config['last'] = $totalPages;
	//上一页
	$up_row  = $nowPage - 1;
	$up_page = $up_row > 0 ? '<a class="prev" href="' . $url.$up_row.$config['html_suffix'] . '">' . $config['prev'] . '</a>' : '';

	//下一页
	$down_row  = $nowPage + 1;
	$down_page = ($down_row <= $totalPages) ? '<a class="next" href="' . $url.$down_row.$config['html_suffix'] . '">' . $config['next'] . '</a>' : '';

	//第一页
	$the_first = '';
	if($totalPages > $rollPage && ($nowPage - $now_cool_page) >= 1){
		$the_first = '<a class="first" href="' .$url.'1'.$config['html_suffix'] . '">' . $config['first'] . '</a>';
	}

	//最后一页
	$the_end = '';
	if($totalPages > $rollPage && ($nowPage + $now_cool_page) < $totalPages){
		$the_end = '<a class="end" href="' . $url.$totalPages.$config['html_suffix'] . '">' . $config['last'] . '</a>';
	}

	//数字连接
	$link_page = "";
	for($i = 1; $i <= $rollPage; $i++){

		if(($nowPage - $now_cool_page) <= 0 ){
			$page = $i;
		}elseif(($nowPage + $now_cool_page - 1) >= $totalPages){
			$page = $totalPages - $rollPage + $i;
		}else{
			$page = $nowPage - $now_cool_page_ceil + $i;
		}
		if($page > 0 && $page != $nowPage){

			if($page <= $totalPages){
				$link_page .= '<a class="num" href="' . $url.$page.$config['html_suffix'] . '">' . $page . '</a>';
			}else{
				break;
			}
				
		}else{
			if($page > 0 && $totalPages != 1){
				$link_page .= '<span class="current">' . $page . '</span>';
			}
		}

	}


	//替换分页内容
	$page_str = str_replace(
			array('%header%', '%nowPage%', '%upPage%', '%downPage%', '%first%', '%linkPage%', '%end%', '%totalRow%', '%totalPage%'),
			array($header, $nowPage, $up_page, $down_page, $the_first, $link_page, $the_end, $totalRows, $totalPages),
			$theme);
	return "<div class=\"pagination\">{$page_str}</div>";
}

/**
 * 获取数据跟分页，通用方法
 * @param unknown $path 跟路径
 * @param unknown $get $_GET
 * @param unknown $map 额外的类型
 * @param unknown $m 数据模型
 * @param unknown $pagesize 一页的记录数，默认为10
 * @return string
 */
function _get_list_data($path,$get,$map,$m,$pagesize,$order){
	if(!$pagesize) $pagesize = 20; //默认为10
	$get['p']?$cur = $get['p']:$cur = 1;
		
	$mapp = $get;
	unset($mapp['_URL_']);
	unset($mapp["__hash__"]);
	$time1 = 0;
	$time2 = date('Y-m-d H:i:s');
	foreach($mapp as $k=>$v){
		if($v){
			if($k != 'start_time' && $k != 'end_time' && $k != 'p' && $k != 'searchtype' && $k != 'keywords'){
				$map[$k] = $v;
			}
			else{
				if($k == 'start_time') $time1 = $v;
				if($k == 'end_time') $time2 = $v;
			}
			if($k != 'p'){
				$path .= $k.'/'.$v.'/';
			}	
			
		}
	}
	if($_GET['searchtype'] && $_GET['keywords']){
		$map[$_GET['searchtype']] = array('like','%'.$_GET['keywords'].'%');
	}
	$map['update_time'] = array('between',array($time1,$time2));
	$data = _uiclist($m,$map,$cur,$pagesize,$order,1);
	if($cur > 1 && count($data) == 0){
		redirect($path.'p/'.($cur-1)); //当前页每页数据、切当前页非第一页，则调到上一页
	}
	
 	//echo $m->_sql(); //打印sql
	$pagetpl = _to_page($data['count'],$cur,$pagesize,$path.'p/');
	
	$result['data'] = $data;
	$result['pagetpl'] = $pagetpl;
	return $result;
}

function _createFolder($path){
	//第一个条件，不能在根目录创建文件夹
	$t = explode('/', $path);
	if(count($t) != 2){
		if (!file_exists($path))
		{
			_createFolder(dirname($path));
			mkdir($path, 0777);
		}
	}
}

/**
 * 删除文件夹及其文件夹下所有文件
 * @param unknown $dir
 * @param unknown $self 是否删除自身
 * @return boolean
 */
function deldir($dir,$self) {
	//先删除目录下的文件：
	$dh=opendir($dir);
	while ($file=readdir($dh)) {
		if($file!="." && $file!="..") {
			$fullpath=$dir."/".$file;
			if(!is_dir($fullpath)) {
				unlink($fullpath);
			} else {
				deldir($fullpath);
			}
		}
	}

	closedir($dh);
	if($self){
		//删除当前文件夹：
		if(rmdir($dir)) {
			return true;
		} else {
			return false;
		}
	}else{
		return true;
	}

}

/*
 * 中文截取，支持gb2312,gbk,utf-8,big5
* @param string $str 要截取的字串
* @param int $start 截取起始位置
* @param int $length 截取长度
* @param string $charset utf-8|gb2312|gbk|big5 编码
* @param $suffix 是否加尾缀
*/

function csubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
	if(function_exists("mb_substr"))
	{
		if(mb_strlen($str, $charset) <= $length) return $str;
		$slice = mb_substr($str, $start, $length, $charset);
	}
	else
	{
		$re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk']          = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5']          = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		if(count($match[0]) <= $length) return $str;
		$slice = join("",array_slice($match[0], $start, $length));
	}
	if($suffix) return $slice."…";
	return $slice;
}

/**
 * 将中文编码
 * @param array $data
 * @returnstring
 */
function ch_urlencode($data) {
	if (is_array($data) || is_object($data)) {
		foreach ($data as $k => $v) {
			if (is_scalar($v)) {
				if (is_array($data)) {
					$data[$k] = urlencode($v);
				} elseif (is_object($data)) {
					$data->$k = urlencode($v);
				}
			} elseif (is_array($data)) {
				$data[$k] = ch_urlencode($v); //递归调用该函数

			} elseif (is_object($data)) {
				$data->$k = ch_urlencode($v);
			}
		}
	}
	return $data;
}
/*
 * 解决json中文编码问题的方法
 */
function ch_json_encode($data) {
	$ret = ch_urlencode($data);
	$ret = json_encode($ret);
	return urldecode($ret);
}

/*
 * 获取随机字符串
 */
function get_rand_char($length){
	$str = null;
	$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
	$max = strlen($strPol)-1;

	for($i=0;$i<$length;$i++){
		$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
	}
	return $str;
}

/*
 * 获取随机字符串
 */
function get_rand_num($length){
	$str = null;
	$strPol = "0123456789";
	$max = strlen($strPol)-1;

	for($i=0;$i<$length;$i++){
		$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
	}
	return $str;
}

/**
 * 可逆加密算法，加密
 * @param unknown $data
 * @param unknown $key
 * @return string
 */
function encrypt($data, $key){
	$key = md5($key);
	$x  = 0;
	$len = strlen($data);
	$l  = strlen($key);
	for ($i = 0; $i < $len; $i++)
	{
		if ($x == $l){
			$x = 0;
		}
		$char .= $key{$x};
		$x++;
	}
	for ($i = 0; $i < $len; $i++){
		$str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
	}
	return base64_encode($str);
}

/**
 * 可逆加密算法，解密
 * @param unknown $data
 * @param unknown $key
 * @return string
 */
function decrypt($data, $key)
{
	$key = md5($key);
	$x = 0;
	$data = base64_decode($data);
	$len = strlen($data);
	$l = strlen($key);
	for ($i = 0; $i < $len; $i++)
	{
		if ($x == $l){
			$x = 0;
		}
		$char .= substr($key, $x, 1);
		$x++;
	}
	for ($i = 0; $i < $len; $i++){
		if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))){
			$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
		}
		else{
			$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
		}
	}
	return $str;
}

//判断微信浏览器打开
function is_weixin()
{
	if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
		return true;
	}
	return false;
}

function error404(){
	header('HTTP/1.1 404 Not Found');
	header("status: 404 Not Found");
}

/**
 * 关键词描红
 * @param unknown $key
 * @param unknown $str
 * @return mixed
 */
function replace_query_str($key,$str){
	return str_replace($key,'<span style="color:red">'.$key.'</span>',$str);
}

/**
 * 处理插件钩子
 * @param string $hook   钩子名称
 * @param mixed $params 传入参数
 * @return void
 */
function hook($hook,$params=array()){
	\Think\Hook::listen($hook,$params);
}
/**
 * 获取插件类的类名
 * @param strng $name 插件名
 */
function get_addon_class($name){
	$class = "Addons\\{$name}\\{$name}Addon";
	return $class;
}

/**
 * 获取插件类的配置文件数组
 * @param string $name 插件名
 */
function get_addon_config($name){
	$class = get_addon_class($name);
	if(class_exists($class)) {
		$addon = new $class();
		return $addon->getConfig();
	}else {
		return array();
	}
}

/**
 * 插件显示内容里生成访问插件的url
 * @param string $url url
 * @param array $param 参数
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function addons_url($url, $param = array()){
	$url        = parse_url($url);
	$case       = C('URL_CASE_INSENSITIVE');
	$addons     = $case ? parse_name($url['scheme']) : $url['scheme'];
	$controller = $case ? parse_name($url['host']) : $url['host'];
	$action     = trim($case ? strtolower($url['path']) : $url['path'], '/');

	/* 解析URL带的参数 */
	if(isset($url['query'])){
		parse_str($url['query'], $query);
		$param = array_merge($query, $param);
	}

	/* 基础参数 */
	$params = array(
			'_addons'     => $addons,
			'_controller' => $controller,
			'_action'     => $action,
	);
	$params = array_merge($params, $param); //添加额外参数

	return U('Addons/execute', $params);
}

//基于数组创建目录和文件
function create_dir_or_files($files){
	foreach ($files as $key => $value) {
		if(substr($value, -1) == '/'){
			mkdir($value);
		}else{
			@file_put_contents($value, '');
		}
	}
}
/**
 * 对查询结果集进行排序
 * @access public
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param array $sortby 排序类型
 * asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list,$field, $sortby='asc') {
	if(is_array($list)){
		$refer = $resultSet = array();
		foreach ($list as $i => $data)
			$refer[$i] = &$data[$field];
		switch ($sortby) {
			case 'asc': // 正向排序
				asort($refer);
				break;
			case 'desc':// 逆向排序
				arsort($refer);
				break;
			case 'nat': // 自然排序
				natcasesort($refer);
				break;
		}
		foreach ( $refer as $key=> $val)
			$resultSet[] = &$list[$key];
		return $resultSet;
	}
	return false;
}
/**
 * 字符串转换为数组，主要用于把分隔符调整到第二个参数
 * @param  string $str  要分割的字符串
 * @param  string $glue 分割符
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function str2arr($str, $glue = ','){
	return explode($glue, $str);
}

/**
 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
 * @param  array  $arr  要连接的数组
 * @param  string $glue 分割符
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function arr2str($arr, $glue = ','){
	return implode($glue, $arr);
}

/**
 * 获取系统中的分组
 * @param array $filter 过滤的分组名
 * @return array 分组数组
 */
function get_dir_file_list($path,$filter){
	//$path = substr(APP_PATH,0,strlen(APP_PATH)-1);
	$data = array();
	if(is_dir($path)){
		$dp=dir($path);
		while($file=$dp->read()){
				
			if($file!='.'&& $file!='..'){
				if($file){
					if(!in_array($file,$filter)){
						$data[] = $file;
					}
				}
			}
				
		}
		$dp->close();
	}
	return $data;
}

/**
 * 获取文件夹下的所有文件路径
 * @param string $dir
 * @return multitype:
 */
function getDir($dir){
	$data=array();
	searchDir($dir,$data);
	return   $data;
}
function searchDir($path,&$data){
	if(is_dir($path)){
		$dp=dir($path);
		while($file=$dp->read()){
			if($file!='.'&& $file!='..'){
				searchDir($path.'/'.$file,$data);
			}
		}
		$dp->close();
	}
	if(is_file($path)){
		$data[]=$path;
	}
}

/**
 * PHP小于5.5 用i_array_column 替代array_column函数
 * @param unknown $input
 * @param unknown $columnKey
 * @param string $indexKey
 * @return multitype:Ambigous <NULL, mixed, unknown> |multitype:
 */
function i_array_column($input, $columnKey, $indexKey=null){
	if(!function_exists('array_column')){
		$columnKeyIsNumber  = (is_numeric($columnKey))?true:false;
		$indexKeyIsNull            = (is_null($indexKey))?true :false;
		$indexKeyIsNumber     = (is_numeric($indexKey))?true:false;
		$result                         = array();
		foreach((array)$input as $key=>$row){
			if($columnKeyIsNumber){
				$tmp= array_slice($row, $columnKey, 1);
				$tmp= (is_array($tmp) && !empty($tmp))?current($tmp):null;
			}else{
				$tmp= isset($row[$columnKey])?$row[$columnKey]:null;
			}
			if(!$indexKeyIsNull){
				if($indexKeyIsNumber){
					$key = array_slice($row, $indexKey, 1);
					$key = (is_array($key) && !empty($key))?current($key):null;
					$key = is_null($key)?0:$key;
				}else{
					$key = isset($row[$indexKey])?$row[$indexKey]:0;
				}
			}
			$result[$key] = $tmp;
		}
		return $result;
	}else{
		return array_column($input, $columnKey, $indexKey);
	}
}

/**
 * 对象转数组
 * @param unknown $array
 * @return array
 */
function object_array($array) {
	if(is_object($array)) {
		$array = (array)$array;
	} if(is_array($array)) {
		foreach($array as $key=>$value) {
			$array[$key] = object_array($value);
		}
	}
	return $array;
}

/**
 * 把全名拆分为姓氏和名字
 * @param string $fullname 全名
 * @return array 一维数组,元素一是姓,元素二为名
 * @author: 风柏杨<waitatlee@163.com>
 */
function splitName($fullname){
	$hyphenated = array('欧阳','太史','端木','上官','司马','东方','独孤','南宫','万俟','闻人','夏侯','诸葛','尉迟','公羊','赫连','澹台','皇甫',
			'宗政','濮阳','公冶','太叔','申屠','公孙','慕容','仲孙','钟离','长孙','宇文','城池','司徒','鲜于','司空','汝嫣','闾丘','子车','亓官',
			'司寇','巫马','公西','颛孙','壤驷','公良','漆雕','乐正','宰父','谷梁','拓跋','夹谷','轩辕','令狐','段干','百里','呼延','东郭','南门',
			'羊舌','微生','公户','公玉','公仪','梁丘','公仲','公上','公门','公山','公坚','左丘','公伯','西门','公祖','第五','公乘','贯丘','公皙',
			'南荣','东里','东宫','仲长','子书','子桑','即墨','达奚','褚师');
	$vLength = mb_strlen($fullname, 'utf-8');
	$lastname = '';
	$firstname = '';//前为姓,后为名
	if($vLength > 2){
		$preTwoWords = mb_substr($fullname, 0, 2, 'utf-8');//取命名的前两个字,看是否在复姓库中
		if(in_array($preTwoWords, $hyphenated)){
			$lastname = $preTwoWords;
			$firstname = mb_substr($fullname, 2, 10, 'utf-8');
		}else{
			$lastname = mb_substr($fullname, 0, 1, 'utf-8');
			$firstname = mb_substr($fullname, 1, 10, 'utf-8');
		}
	}else if($vLength == 2){//全名只有两个字时,以前一个为姓,后一下为名
		$lastname = mb_substr($fullname ,0, 1, 'utf-8');
		$firstname = mb_substr($fullname, 1, 10, 'utf-8');
	}else{
		$lastname = $fullname;
	}
	return array($lastname, $firstname);
}
